<?php
/**
 * 会員APIコントローラー
 *
 * @package  app
 * @extends  Controller
 */
class Controller_Api_Favorite extends Controller_Apibase {
	/**
	 * お気に入り取得
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_get() {
		$query = DB::select('song.song_title', 'song.artist', 'artwork', 'preview');
		$query -> from('favorite');
		$query -> where($this -> member_where_other);
		$query -> join('song') -> on('favorite.song_id', '=', 'song.song_id');
		$query -> join('itunes_song','LEFT') -> on('song.itunes_track_id', '=', 'itunes_song.itunes_track_id');
		$query -> order_by('favorite_id', 'desc');
		$query -> limit(Config::get('maxrows_favoritelist'));
		$favorite = $query -> execute() -> as_array();
		
		return Response::forge(json_encode($favorite), D_HTTP_UPDATE);
	}
	
	/**
	 * お気に入り登録
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_post() {
		$post = Input::post();

		// 登録済みチェック
		$song = $this -> get_song($this -> song_where);
		$values = $this -> member_where_other;
		$values['song_id'] = $song["song_id"];

		$query = DB::select(DB::expr('COUNT(*) AS count'));
		$query -> from('favorite');
		$query -> where($values);
		$result = $query -> execute();

		if ($result[0]['count'] == 0) {
			// お気に入りを登録
			$query = DB::insert('favorite');
			$query -> set($values);
			$query -> execute();

			// 累計
			$query = DB::update('song');
			$query -> set(array('count_favorite' => DB::expr('count_favorite + 1')));
			$query -> where('song_id', $song['song_id']);
			$query -> execute();

			return Response::forge(null, D_HTTP_UPDATE);
		} else {
			// 既に登録済み
			Log::info('favorite exists');
			return Response::forge(null, D_HTTP_WARNING);
		}

	}

	/**
	 * お気に入り削除
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_delete() {
		$post = Input::post();

		// 登録済みチェック
		$song = $this -> get_song($this -> song_where);
		$values = $this -> member_where_other;
		$values['song_id'] = $song["song_id"];

		$query = DB::select('song_id');
		$query -> from('favorite');
		$query -> where($values);
		$result = $query -> execute();

		if (count($result) != 0) {
			// お気に入りを削除
			$query = DB::delete('favorite');
			$query -> where($values);
			$query -> execute();

			return Response::forge(null, D_HTTP_UPDATE);
		} else {
			// 存在しない
			Log::info('favorite none');
			return Response::forge(null, D_HTTP_WARNING);
		}

	}

}
